<?php

declare(strict_types=1);

namespace App\Controller\WebSocket;

use App\Game\Server\GameServer;
use App\Game\Server\HallServer;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Di\Annotation\Inject;


class SocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{

    /**
     * 大厅服务
     * @Inject
     * @var HallServer
     */
    private $hallServer;

    /**
     * 游戏服务
     * @Inject
     * @var GameServer
     */
    private $gameServer;

    public function onClose($server, int $fd, int $reactorId): void
    {
       $this->hallServer->logout($server, $fd);
    }

    public function onMessage($server, \Swoole\WebSocket\Frame $frame): void
    {
        //解析数据
        $data = @json_decode($frame->data, true);
        if (!$data) {
            stdLog()->warning("{$frame->fd} 参数错误 $data");
            $server->push($frame->fd, json_encode(error('数据格式错误'), JSON_UNESCAPED_UNICODE));
            return;
        }
        //组合参数
        $params = $data['params'] ?? [];    //参数
        $params['fd'] = $frame->fd;
        //返回格式
        $next = function($response) use ($server, $params) {
            $response['request_id'] = $params['request_id'] ?? 0;
            return $server->push($params['fd'], json_encode($response, JSON_UNESCAPED_UNICODE));
        };
        //检查命令
        $_server = $data['_server'] ?? '';   //服务
        $cmd = $data['cmd'] ?? '';          //命令
        if (!$cmd) {
            $next(error('命令参数错误'));
        }
        dump($params);
        //服务器
        if ($_server == 'hall') {
            if (!$cmd || !method_exists($this->hallServer, $cmd)) {
                $next(error('未识别的命令'));
                return;
            }
            //执行逻辑
            $this->hallServer->$cmd($next, $server, $params);
        } else if ($_server == 'game') {
            if (!$cmd || !method_exists($this->gameServer, $cmd)) {
                $next(error('未识别的命令'));
                return;
            }
            //执行逻辑
            $this->gameServer->$cmd($next, $server, $params);
        } else {
            $next(error('未识别的服务'));
            return;
        }
    }

    public function onOpen($server, \Swoole\Http\Request $request): void
    {

    }
}